/*********************************************************************************
 *      Copyright:  (C) 2020 Juan
 *                  All rights reserved.
 *
 *       Filename:  thread.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(22/07/20)
 *         Author:  wangruijie <1046299465@qq.com>
 *      ChangeLog:  1, Release initial version on "22/07/20 06:44:03"
 *                 
 ********************************************************************************/
#include"G4module_server.h"

/* ***************************************************************************
 * 函数名：accept_new_thread()
 * 功能：每当accept出一个新的socket_fd时，调用这个函数，创建一个新线程，在新线程里与client做交互
 * 参数：sock
 * 返回值：
 * ***************************************************************************/
void accept_new_thread(int sock)
{
    pthread_t        thread;

    pthread_create(&thread,NULL,process_in_new_thread_when_accepted,(void*)sock);
    pthread_detach(thread);
}

/* ***************************************************************************
 * 函数名：process_in_new_thread_when_accepted
 * 功能：main执行accept()得到新socket_fd的时候，执行这个函数，创建一个新线程，在新线程里反馈给client收到的信息
 * 参数：arg
 * 返回值：
 * ***************************************************************************/
void* process_in_new_thread_when_accepted(void* arg)
{
    long                         long_fd = (long)arg;
    int                          fd = (int)long_fd;
    struct event_base            *base;
    struct event                 *read_ev;
    struct sock_ev               *event_struct;
    char                         buffer[1024];

    if(fd < 0)
    {
        printf("process_in_new_thread_when_accepted() quit!");
        return 0;
    }

    /* 初始化base，读事件和写事件 */
    base = event_base_new();
    read_ev = (struct event*)malloc(sizeof(struct event));

    /* 将base，read_ev,write_ev封装到一个event_struct对象里，便于销毁 */
    event_struct = (struct sock_ev*)malloc(sizeof(struct sock_ev));
    event_struct->base = base;
    event_struct->read_ev = read_ev;

    /* 对读事件进行相应的设置 */
    event_set(read_ev, fd, EV_READ|EV_PERSIST, on_read, event_struct);
    event_base_set(base, read_ev);
    event_add(read_ev, NULL);
    printf("1receive data:%s\n", buffer);

    /* 开始libevent的loop循环 */
    event_base_dispatch(base);
    event_base_free(base);
}

